package FlickrGeoTagr.GPSReaders {
	public class RMCReader extends ReaderInterface {
		
		public function RMCReader(log:String) {
			super();
			_log = new Array();
			var logEntries:Array = log.split("\n");
		
			for(var i:Number = 1; i < logEntries.length; i++) {
				var logEntry:Array = logEntries[i].split(",");
				if (logEntry.length == 13) {
					var entryDate:Date = convertDate(logEntry[9],logEntry[1]);
					
					if (_startDate == null) {
						_startDate = new Date(entryDate);
					} else if (_startDate.getTime() > entryDate.getTime()) {
						_startDate = new Date(entryDate);
					}
					
					if (_endDate == null) {
						_endDate = new Date(entryDate);
					} else if (_endDate.getTime() < entryDate.getTime()) {
						_endDate = new Date(entryDate);
					}
								
					_log.push({
						Id: _log.length,
						Time: entryDate,
						OffsetTime: entryDate,
						Latitude: convertGpsCoordinate(logEntry[3],logEntry[4]),
						Longitude: convertGpsCoordinate(logEntry[5],logEntry[6])
					})
				}
			}
			
			_log.sort(compareEntry);
		}
		
		private function compareEntry(entryA:Object, entryB:Object):Number {
			var timeA:Date = new Date(entryA.Time);
			var timeB:Date = new Date(entryB.Time);
			if (timeA.getTime() < timeB.getTime()) {
				return -1;
			} else if (timeA.getTime() > timeB.getTime()) {
				return 1;
			}
			return 0;
		}
		
		private function convertGpsCoordinate(coordinate:String, direction:String):String {
			var degrees:String = coordinate.slice(0, coordinate.indexOf(".")-2);
			var decimal:Number = Number(coordinate.slice(coordinate.indexOf(".")-2)) / 60;
			if (direction == "N" || direction == "E") {
				return degrees + decimal.toString().slice(1,6);
			}
			return "-" + degrees + decimal.toString().slice(1,6);
		}
		
		private function convertDate(originalDate:String, originalTime:String):Date {
			var date:Number = Number(originalDate.slice(0, 2));
			var month:Number = Number(originalDate.slice(2,4));
			var year:Number = 2000 + Number(originalDate.slice(4,6));
			var hour:Number = Number(originalTime.slice(0,2));
			var minute:Number = Number(originalTime.slice(2,4));
			var second:Number = Number(originalTime.slice(4,6));
			return new Date(Date.UTC(year, month-1, date, hour, minute, second));
		}
		
		public function offsetTime(hourOffset:Number, minuteOffset:Number):void {
			for each(var entry:Object in _log) {
				var newTime:Date = new Date(entry.Time);
				newTime.hours += hourOffset;
				newTime.minutes += minuteOffset;
				entry.OffsetTime = newTime;
			}
			
			_startDate.hours += hourOffset;
			_startDate.minutes += minuteOffset;
				
			_endDate.hours += hourOffset;
			_endDate.minutes += minuteOffset;
		}
	}
}